import Modals from '@/components/modals/Modals';
import React, { Suspense, useEffect, useState } from 'react';
import { useKnowledgeStore } from '@/store/knowledge';
import { OptimizedistType } from '@/types/know/know';
import datasetService from '@/api/services/datasetService';
import useModal from '@/hooks/use-modal/useModal';
import TipsModals from '@/components/modals/TipsModals';
import knowService from '@/api/services/knowService';
const DocumentProcessingWronglyModals = React.lazy(
  () => import('./DocumentProcessingWronglyModals'), //错别字
);
const DocumentViolationHandlingModals = React.lazy(
  () => import('./DocumentViolationHandlingModals'), //敏感词
);
const DocumentRepetitionModals = React.lazy(() => import('./DocumentRepetitionModals')); //重复
const DocumentProcessingModals = React.lazy(() => import('./DocumentProcessingModals')); //文档优化
interface DocumentModalsProps {
  visible: boolean;
  onCancel: () => void;
  type: 'wrongly' | 'optimization' | 'sensitive' | 'repetition';
  collectionItem: OptimizedistType;
}

const DocumentModals = ({ visible, onCancel, type, collectionItem }: DocumentModalsProps) => {
  const {
    listLength,
    setPrefetchedWrongly,
    setPrefetchedSensitive,
    setPrefetchedRepetition,
    setListLength,
  } = useKnowledgeStore();
  const [flag, setFlag] = useState<boolean | undefined>(undefined);
  const modal = useModal('delete');
  const changeAllIgnore = async () => {
    // 单类页面沿用原有子组件逻辑
    setFlag(!flag);
    return; //暂时先隐藏
    const typeArr = collectionItem?.optimize_text || [];
    if (!Array.isArray(typeArr) || typeArr.length === 0) return;
    const { collectionId, appId, datasetId } = collectionItem as any;

    const hasWrong = typeArr.some((t) => t.includes('错别字'));
    const hasSensitive = typeArr.some((t) => t.includes('敏感词'));
    const hasRepeat = typeArr.some((t) => t.includes('重复'));

    const tasks: Promise<any>[] = [];
    if (hasWrong) {
      tasks.push(
        knowService.ignoreAutoCorrect({
          type: 'correct',
          status: 1,
          ignoreList: [{ collectionId, appId }],
        } as any),
      );
    }
    if (hasSensitive) {
      tasks.push(
        knowService.ignoreAutoCorrect({
          type: 'sensitive',
          status: 1,
          ignoreList: [{ collectionId, appId }],
        } as any),
      );
    }
    if (hasRepeat) {
      //这个接口有问题，需要改
      tasks.push(knowService.similarityIngore({ datasetId, collectionId }));
    }

    await Promise.allSettled(tasks);
    // 清空缓存与列表长度，使“完成”可用
    if (hasWrong)
      setPrefetchedWrongly({ collectionId, appId, auto_correct_pairs_with_count: [], trunks: [] });
    if (hasSensitive)
      setPrefetchedSensitive({
        collectionId,
        appId,
        all_sensitive_words_with_count: [],
        trunks: [],
      });
    if (hasRepeat) setPrefetchedRepetition({ collectionId, appId, data: [] });
    setListLength(0);
  };

  const getChildren = () => {
    const childKey = `${type}-${collectionItem?.collectionId || ''}`;
    if (type === 'wrongly') {
      return (
        <DocumentProcessingWronglyModals
          key={childKey}
          collectionItem={collectionItem}
          flag={flag}
        />
      );
    } else if (type === 'sensitive') {
      return (
        <DocumentViolationHandlingModals
          key={childKey}
          collectionItem={collectionItem}
          flag={flag}
        />
      );
    } else if (type === 'repetition') {
      return (
        <DocumentRepetitionModals key={childKey} collectionItem={collectionItem} flag={flag} />
      );
    } else {
      return (
        <DocumentProcessingModals
          key={childKey}
          collectionItem={collectionItem}
          flag={flag}
          setFlag={setFlag}
          deleteDatasetFile={deleteDatasetFile}
        />
      );
    }
  };
  //删除文档
  const deleteDatasetFile = async () => {
    try {
      await datasetService.deleteDatasetFile({
        ids: [collectionItem.collectionId],
      });
      modal.delete.close();
      onCancel();
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      if (type !== 'optimization' || !collectionItem) return;
      const typeArr = collectionItem?.optimize_text || [];
      if (!Array.isArray(typeArr) || typeArr.length === 0) return;
      const { collectionId, appId } = collectionItem;

      try {
        // 按需分别请求，避免重复
        if (typeArr.some((t) => t.includes('错别字'))) {
          const res = await knowService.autoCorrectList(collectionId, appId);
          setPrefetchedWrongly({
            collectionId,
            appId,
            auto_correct_pairs_with_count: res.auto_correct_pairs_with_count || [],
            trunks: res.trunks || [],
          });
        }
        if (typeArr.some((t) => t.includes('敏感词'))) {
          const res = await knowService.sensitiveDetectionList(collectionId, appId);
          setPrefetchedSensitive({
            collectionId,
            appId,
            all_sensitive_words_with_count:
              res.all_sensitive_words_with_count || res.auto_correct_pairs_with_count || [],
            trunks: res.trunks || [],
          });
        }
        if (typeArr.some((t) => t.includes('重复'))) {
          const res = await knowService.getSimilarityList(collectionId, appId, 1, 10, 0);
          setPrefetchedRepetition({ collectionId, appId, data: res.data || [] });
        }
      } catch (e) {
        // 静默失败，避免影响弹窗展示
      }
    };
    setFlag(undefined);
    // fetchData();   暂时先隐藏
  }, [type, collectionItem]);

  return (
    <>
      <Modals
        open={visible}
        onCancel={onCancel}
        title={
          <div>
            文档
            {type === 'wrongly'
              ? '错别字'
              : type === 'sensitive'
              ? '敏感词'
              : type === 'repetition'
              ? '重复'
              : '优化'}
          </div>
        }
        width={1100}
        maskClosable={false}
        headerHeight={0}
        modelContentClassName={`${type === 'optimization' && 'py-2'}`}
        footer={
          <div className="flex justify-end gap-2 border-t border-t-line-2 p-3">
            <div
              className={`ml-4 flex h-[32px] w-[88px] cursor-pointer items-center justify-center rounded-md border 
               !border-@brand-color !text-@brand-color
          `}
              onClick={changeAllIgnore}
            >
              忽略全部
            </div>

            {type === 'repetition' ? (
              <div
                className={`ml-4 flex h-[32px] cursor-pointer items-center justify-center rounded-md border !border-@error-color !bg-@error-color 
               px-2 py-1 !text-white
          `}
                onClick={modal.delete.open}
              >
                删除文档
              </div>
            ) : (
              <div
                style={
                  listLength === 0
                    ? { background: 'linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%)' }
                    : {}
                }
                className={`ml-4 flex h-[32px] w-[68px]  items-center justify-center rounded-md border text-white 
                 ${
                   listLength === 0
                     ? 'cursor-pointer !border-@brand-color '
                     : '!border-@brand-disabled cursor-not-allowed !bg-@brand-color-disabled'
                 }
            `}
                onClick={() => {
                  if (listLength === 0) {
                    onCancel();
                  }
                }}
              >
                完成
              </div>
            )}
          </div>
        }
      >
        <div className=" overflow-hidden">
          <Suspense fallback={<div className="p-4 text-center text-sm text-text-3">加载中...</div>}>
            {visible && getChildren()}
          </Suspense>
        </div>
      </Modals>
      <TipsModals
        okText="删除"
        centered
        open={modal.delete.isOpen}
        onOk={deleteDatasetFile}
        onCancel={modal.delete.close}
      >
        <p>确定要删除文档【{collectionItem.fileName}】吗？</p>
      </TipsModals>
    </>
  );
};

export default DocumentModals;
